<?php
class CartBusiness
{

	public function getCart($id){
		$db = Zend_Db_Table::getDefaultAdapter();

		$select = $db->fetchAll("select * from cl_cart ca
								inner join cl_client ce
								on ce.id_client = ca.id_client
								inner join pr_product pr
								on pr.id_product = ca.id_product
								where ca.id_client = '".$id."'");

		return $select;
	}

	public function countItems($id){
		try {
			$db = Zend_Db_Table::getDefaultAdapter();
			//Query de consulta
			$query = $db->select()
			->from('cl_cart')
			->where('id_client = ?', $id);
			$select = $db->fetchAll($query);
			return sizeof($select);
		} catch (Exception $e) {
		}

	}

	public function addToCart($array){
		try {
			$db = Zend_Db_Table::getDefaultAdapter();

			$old = $db->fetchAll("select ca.id_product from cl_cart ca where ca.id_product = '".$array['id_product']."' and ca.id_client = ".$array['id_client']." ");
				
			if($old[0]['id_product'] != $array['id_product']){
					
				$lastId = $db->lastInsertId('cl_cart');
				$array['id_cart'] = $lastId;
				$query = $db->insert('cl_cart', $array);
					
			}

		} catch (Exception $e) {
			echo $e;
		}
	}

	public function alterCart($id, $qtd){
		try {
			$db = Zend_Db_Table::getDefaultAdapter();

			$query = ("update cl_cart set qtd = '".$qtd."' where id_cart = '".$id."' ");

			echo $query;

			$db->query($query);
		} catch (Exception $e){
			echo $e;
		}
	}

	public function deleteItems($id){
		try {
			$db = Zend_Db_Table::getDefaultAdapter();

			$query = ("delete from cl_cart where id_cart = '".$id."' ");

			echo $query;

			$db->query($query);
		} catch (Exception $e){
			echo $e;
		}
	}

	public function dropCart($client){
		try {
			$db = Zend_Db_Table::getDefaultAdapter();

			$query = ("delete from cl_cart where id_client = '".$client."' ");

			$db->query($query);
		} catch (Exception $e){
			echo $e;
		}
	}

	public function findProductById($id) {
		try {
			$category = new Category();
			$db = Zend_Db_Table::getDefaultAdapter();
			$query = $db->select()
			->from('pr_product')
			->where('id_product = ?', $id);
			$result = $db->fetchAll($query);
			return $result;
		} catch (Exception $e) {
		}
	}
}